<template>
  <div>
    <el-card>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>通知管理</el-breadcrumb-item>
        <el-breadcrumb-item>通知详情</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-card style="margin-top: 8px">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="标题名称">
          <el-input
            v-model="queryForm.infortitle"
            placeholder="请输入标题关键字"
            clearable
          />
        </el-form-item>
        <el-form-item label="发布人">
          <el-input
            v-model="queryForm.fbr"
            placeholder="请输入发布人关键字"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        style="width: 100%; margin-top: 10px"
        :data="tableData"
        border
        stripe
        :loading="loading"
      >
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="infortitle" label="标题名称" />
        <el-table-column prop="fbr" label="发布人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? "开启" : "关闭" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row.id)">
              查看内容
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px; display: flex; justify-content: flex-end">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="detailData">
        <div class="detail-header">
          <h3>{{ detailData.infortitle || "-" }}</h3>
          <div class="detail-meta">
            <span>发布人：{{ detailData.fbr || "-" }}</span>
            <span>状态：{{ detailData.status === 1 ? "开启" : "关闭" }}</span>
            <span>发布时间：{{ formatDate(detailData.createtime) }}</span>
          </div>
        </div>
        <el-divider />
        <div class="detail-content">
          <p v-if="detailData.content">{{ detailData.content }}</p>
          <el-empty v-else description="暂无内容" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";

interface InformRow {
  id: number;
  infortitle: string;
  status: number;
  fbr: string;
  createtime: string;
}

interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const loading = ref(false);
const tableData = ref<InformRow[]>([]);

const queryForm = reactive({
  infortitle: "",
  fbr: "",
});

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  pageCount: 0,
});

const detailDialogVisible = ref(false);
const detailData = ref<any>(null);

const fetchTableData = () => {
  loading.value = true;
  const params: any = {
    pageindex: pagination.pageindex,
    pagesize: pagination.pagesize,
  };
  if (queryForm.infortitle) params.infortitle = queryForm.infortitle;
  if (queryForm.fbr) params.fbr = queryForm.fbr;

  https.Reads
    .get<ApiPageingResponse<InformRow>>("/Manage/ShowInfor", { params })
    .then((res) => {
      const response = res.data;
      if (response.code === 1) {
        tableData.value = response.data || [];
        pagination.totalCount = response.totalCount || 0;
        pagination.pageCount = response.pageCount || 0;
      } else {
        tableData.value = [];
        pagination.totalCount = 0;
        pagination.pageCount = 0;
        ElMessage.error(response.msg || "获取通知列表失败");
      }
    })
    .catch((error) => {
      console.error("获取通知列表失败:", error);
      tableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
      ElMessage.error("获取通知列表失败，请稍后再试");
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  fetchTableData();
});

const handleQuery = () => {
  pagination.pageindex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.infortitle = "";
  queryForm.fbr = "";
  handleQuery();
};

const handleSizeChange = (val: number) => {
  pagination.pagesize = val;
  pagination.pageindex = 1;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageindex = val;
  fetchTableData();
};

const viewDetail = (id: number) => {
  https.Reads
    .get<ApiResultResponse<any>>("/Manage/GetInforId", { params: { id } })
    .then((res) => {
      if (res.data.code === 1) {
        detailData.value = res.data.data;
        detailDialogVisible.value = true;
      } else {
        ElMessage.error(res.data.msg || "获取通知详情失败");
      }
    })
    .catch((error) => {
      console.error("获取通知详情失败:", error);
      ElMessage.error("获取通知详情失败，请稍后再试");
    });
};

const formatDate = (val: string) => {
  if (!val) return "";
  const d = new Date(val);
  if (Number.isNaN(d.getTime())) return val;
  const pad = (n: number) => `${n}`.padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(
    d.getHours()
  )}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
</script>

<style scoped>
.detail-header {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.detail-content {
  min-height: 200px;
  white-space: pre-wrap;
  line-height: 1.6;
  color: #303133;
}
</style>
